import { reactive, ref } from 'vue';
import { update } from '@/services';
import { message } from 'ant-design-vue';
import md5 from 'js-md5';

export default function usePasswordData() {
  const passwordFormRef = ref(null);
  const passwordFormState = reactive({
    id: '',
    password: '',
    doublePassword: '',
    originalPassword: '',
  });

  const isPasswordModalVisible = ref(false);


  const handlePasswordOk = async () => {
    try {
      await passwordFormRef.value.validate();
    } catch (error) {
      message.error('表单验证失败，请检查输入');
      return;
    }

    const { success, data, code, msg } = await update(`/api/auth/rbacUser`, {
      id: passwordFormState.id,
      password: md5(passwordFormState.password),
      originalPassword: md5(passwordFormState.originalPassword),
    });
    if (success && data) {
      message.info(`保存成功`);
      isPasswordModalVisible.value = false;

      return;
    }
  };
  const validatePassword = (rule: any, value: string) => {
    const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    if (!value) {
      return Promise.reject('请输入密码');
    }
    if (!passwordPattern.test(value)) {
      return Promise.reject('密码必须至少8位，并包含大小写字母、数字和特殊字符');
    }
    return Promise.resolve();
  };
  const validateDoublePassword = (rule: any, value: string) => {
    if (!value) {
      return Promise.reject('请确认密码');
    }

    if (isPasswordModalVisible.value && value !== passwordFormState.password) {
      return Promise.reject('两次输入的密码不一致');
    }
    return Promise.resolve();
  };

  const showPasswordModal= id => {
    passwordFormState.id = id;
    isPasswordModalVisible.value = true;
  };

  return {
    passwordFormRef,
    passwordFormState,
    isPasswordModalVisible,
    showPasswordModal,
    handlePasswordOk,

    validatePassword,
    validateDoublePassword,
  };
}
